<!--
 * @Author: sdorein sdorein@163.com
 * @Date: 2024-09-11 17:07:05
 * @LastEditors: sdorein sdorein@163.com
 * @LastEditTime: 2024-09-11 17:08:54
 * @FilePath: \vite-web\src\views\compress.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
	<div class="content">
		<div class="infoItem">
			<div class="leftCont"><span>*</span>照片：</div>
			<div class="rightCont rightImg">
				<div class="imgList">
					<div v-for="(item, ind) in imgFiles" :key="ind">
						<div class="imgItem">
							<div class="remove" @click="removeImg(ind)">
								<image src="/static/img/delete.png"></image>
							</div>
							<image :src="item" alt="" @click="previewImg(ind)" mode="aspectFit"
								style="width: 50px; height: 50px"></image>
						</div>
					</div>
				</div>
				<div class="addImg" @click="chooseImg">
					<div class="addImgBtn">+</div>
				</div>
			</div>
		</div>
		<canvas class="canvas" canvas-id="canvas" :style="{
        width: cWidth + 'px',
        height: cHeight + 'px',
        visibility: 'hidden',
        position: 'absolute',
        'z-index': '-1',
        left: '-10000rpx',
        top: '-10000rpx',
      }"></canvas>
	</div>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import Util from '../../utils/util.ts';
	const cWidth = ref(2000);
	const cHeight = ref(2000);
	const mapCtx = ref({});
	const imgFiles = ref([]);
	const compressImgs = ref([]);

	const chooseImg = (e) => {
		let maxSize = 150;
		let dWidth = uni.getSystemInfoSync().windowWidth;
		console.log(dWidth);
		uni.chooseImage({
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			success: function(res) {
				// 返回选定图片的本地文件列表，tempFilePaths可以作为img标签的src列表
				// 当一次选择多张图片的情况
				res.tempFilePaths.forEach((v) => {
					imgFiles.value.push(v);
					uni.getFileInfo({
						filePath: v,
						success: function(res) {
							var cW = res.width,
								cH = res.height,
								rat = 1.1;
							cWidth.value = cW;
							cHeight.value = cH;
						},
					});
					Util.getLessLimitSizeImage('canvas', v, maxSize, dWidth, function(img) {
						compressImgs.value.push(img);
						uni.getFileInfo({
							filePath: img,
							success: function(res) {
								console.log('压缩后：' + res.size / 1024 + 'kb');
							},
						});
					});
				});
			},
			fail: function(err) {
				console.log(err);
			},
		});
	};
	// 预览图片
	const previewImg = (ind) => {
		uni.showActionSheet({
			itemList: ['预览', '删除'],
			success: function(res) {
				if (res.tapIndex == 0) {
					uni.previewImage({
						current: imgFiles.value[ind],
						urls: imgFiles.value,
					});
				} else {
					imgFiles.value.splice(ind, 1);
				}
			},
		});
	};
</script>

<style lang="scss" scoped></style>